"""
@Time ： 2025/9/5 09:09
@Auth ： zh
@File ：delete_project.py
"""
# 批量获取项目id执行删除个人库数据（仅删除前10个）
import requests
import json
from datetime import datetime

def batch_delete_quota():
    # -------------------------- 1. 基础配置 --------------------------
    # 提取ID的请求地址
    list_url_test = "https://test.icii.agtsci.cn/api/cis/quota/personal/list"
    list_url_prod = "https://icii.agt.cn/api/cis/quota/personal/list"
    # 删除操作的请求地址
    delete_url_test = "https://test.icii.agtsci.cn/api/cis/quota/personal/delete"
    delete_url_prod = "https://icii.agt.cn/api/cis/quota/personal/delete"
    # 请求头（含Authorization令牌，需确保令牌未过期）
    headers = {
        "Authorization": "bearer 7923221f-908b-4cea-af38-e05d21ff9aa0",
        "Content-Type": "application/json"
    }
    # 提取ID时的请求参数（与原请求一致，分页获取数据）
    list_params = {
        "regionId": "",
        "categoryId": "",
        "keyword": "",
        "startTime": "",
        "endTime": "",
        "orderFields": [],
        "deleted": False,
        "auditStatus": "",
        "fileKind": "",
        "pageNumber": 1,  # 分页起始页
        "pageSize": 30     # 每页数量
    }

    # -------------------------- 2. 提取前10个ID --------------------------
    all_quota_ids = []  # 存储需要删除的ID
    max_count = 10      # 限制只获取前10个
    print(f"[{datetime.now()}] 开始提取前{max_count}个配额ID...")

    try:
        while True:
            # 发送获取列表的POST请求
            list_response = requests.post(
                url=list_url_test,
                headers=headers,
                data=json.dumps(list_params)
            )
            list_response.raise_for_status()
            list_result = list_response.json()

            if list_result.get("code") != 200:
                raise Exception(f"获取列表失败：{list_result.get('message', '未知错误')}")

            # 提取当前页的ID
            current_page_list = list_result.get("data", {}).get("list", [])
            current_ids = [item.get("id") for item in current_page_list if item.get("id")]

            # 计算还需要多少个ID才能达到目标数量
            need_count = max_count - len(all_quota_ids)
            if need_count > 0:
                # 只取需要的数量（避免超过10个）
                take_ids = current_ids[:need_count]
                all_quota_ids.extend(take_ids)
                print(f"[{datetime.now()}] 已提取{len(all_quota_ids)}/{max_count}个ID")
            else:
                # 已经收集到足够的ID，提前退出
                break

            # 检查是否已收集到足够的ID
            if len(all_quota_ids) >= max_count:
                break

            # 准备下一页请求
            total_count = int(list_result.get("data", {}).get("total", 0))
            current_page = list_params["pageNumber"]
            total_page = (total_count + list_params["pageSize"] - 1) // list_params["pageSize"]

            if current_page >= total_page:
                break  # 没有更多数据了
            list_params["pageNumber"] += 1

    except Exception as e:
        print(f"[{datetime.now()}] 提取ID失败：{str(e)}")
        return

    # 检查是否有ID需要删除
    if not all_quota_ids:
        print(f"[{datetime.now()}] 未提取到任何配额ID，无需删除")
        return
    print(f"[{datetime.now()}] ID提取完成，共需删除 {len(all_quota_ids)} 个配额\n")

    # -------------------------- 3. 批量执行删除操作 --------------------------
    print(f"[{datetime.now()}] 开始批量删除...")
    success_count = 0
    fail_records = []

    for idx, quota_id in enumerate(all_quota_ids, 1):
        delete_params = {"quotaId": quota_id}
        try:
            delete_response = requests.post(
                url=delete_url_test,
                headers=headers,
                data=json.dumps(delete_params)
            )
            delete_response.raise_for_status()
            delete_result = delete_response.json()

            if delete_result.get("code") == 200:
                success_count += 1
                print(f"[{datetime.now()}] 第{idx}/{len(all_quota_ids)}个：ID={quota_id} 删除成功")
            else:
                raise Exception(f"业务失败：{delete_result.get('message', '未知错误')}")

        except Exception as e:
            fail_msg = f"ID={quota_id}，原因：{str(e)}"
            fail_records.append(fail_msg)
            print(f"[{datetime.now()}] 第{idx}/{len(all_quota_ids)}个：{fail_msg}")

    # -------------------------- 4. 输出删除结果 --------------------------
    print(f"\n[{datetime.now()}] 批量删除操作完成！")
    print(f"总任务数：{len(all_quota_ids)}")
    print(f"成功数：{success_count}")
    print(f"失败数：{len(fail_records)}")
    if fail_records:
        print("失败详情：")
        for idx, fail_msg in enumerate(fail_records, 1):
            print(f"  {idx}. {fail_msg}")

if __name__ == "__main__":
    batch_delete_quota()